<template>
  <el-dialog :visible.sync="showJsonDialog" title="JSON图形化" width="80%" center>
    <div class="hor-layout dialog-content">
      <div style="height: 100%;width:250px">
        <el-input class="code-content" type="textarea" :rows="15" v-model="jsonStr" @change="jsonChange"></el-input>
      </div>
      <div class="json-content-layout hor-layout">
        <BaseObj :json-data="jsonData" @objBack="objBack"></BaseObj>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="info" size="small" @click="closeDialog">取消</el-button>
      <el-button type="primary" size="small" @click="saveData">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import BaseObj from "./base-obj";

const dataTypeOf = (data) => {
  return Object.prototype.toString.call(data).toLowerCase()
}
const isTypeObjectStr = (jsonStr) => {
  try {
    return dataTypeOf(JSON.parse(jsonStr)) == "[object object]"
  } catch (e) {
    return false
  }
}
export default {
  name: "jsonMap",
  components: {BaseObj},
  data() {
    return {
      jsonStr: "",
      jsonData: {},
      showJsonDialog: false
    }
  },
  methods: {
    openDialog(jsonStr) {
      this.jsonStr = jsonStr && isTypeObjectStr(jsonStr) ? jsonStr : "{}"
      this.jsonData = JSON.parse(this.jsonStr)
      this.showJsonDialog = true
    },
    closeDialog() {
      this.showJsonDialog = false
    },
    saveData() {
      this.$emit("objDataBack", this.jsonStr)
      this.showJsonDialog = false
    },
    objBack(data) {
      this.jsonData = data
      this.jsonStr = JSON.stringify(data)
    },
    jsonChange() {
      this.jsonData = JSON.parse(this.jsonStr)
    }
  }
}
</script>

<style scoped>
.json-content-layout {
  margin-left: 35px;
  width: 100%;
  height: 300px;
}

.hor-layout {
  display: flex;
  flex-direction: row;
}

.dialog-content {

}

.code-content {
  padding: 10px;
  border-radius: 10px;
  color: #000000ff;
  background-color: #cbcbcb;
  border: 1px solid #dddddd;
  /*  */
  width: 100%;
  white-space: pre-wrap;
  font-family: 'Courier New', Courier, monospace;
  font-size: 16px;
  font-weight: bold;
  line-height: 25px;
}
</style>
